package com.zhou;

import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

import org.jsoup.*;
import org.jsoup.nodes.*;
import org.openqa.selenium.*;
import org.openqa.selenium.By.*;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.interactions.Actions;

public class Main {
    // 登录地址
    private String loginUrl = "http://www.pss-system.gov.cn/sipopublicsearch/portal/uilogin-forwardLogin.shtml";
    private String firstHandle = "";
    private String secondHandle = "";
    private String thirdHandle = "";

    public static void main(String[] args) {
        MyForm myForm = new MyForm();
    }

    public void fun4() {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                // 13175
                download(12275, 20001, "表二", "muronghuoxiao3", "19940203XIN");
            }
        });

        t1.start();
        // delay(60000);
        // t3.start();
        // delay(60000);
        // t4.start();
    }

    public void fun3() {
        // System.setProperty("phantomjs.binary.path",
        // "C:\\Windows\\phantomjs.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.baidu.com");
    }

    public void fun2() {

        List<InfoEntity> infoEntityList = new ArrayList<InfoEntity>();

        // 设置ChromDriver的属性
        ChromeOptions options = new ChromeOptions();
        // 设置无头模式
        // options.addArguments("--headless");
        options.addArguments("--disable-gpu");
        // 设置最大化显示
        options.addArguments("--start-maximized");
        WebDriver driver = new ChromeDriver();

        // 加载登录界面
        driver.get(loginUrl);

        delay(100);

        // 获得登录窗口
        WebElement username = driver.findElement(By.id("j_username"));
        WebElement password = driver.findElement(By.id("j_password_show"));
        WebElement captcha = driver.findElement(By.id("j_validation_code"));
        WebElement rememberPassword = driver.findElement(By
                .id("wee_remember_me"));
        WebElement login = driver.findElement(new ByCssSelector(
                "[class='btn btn-login']"));

        // 写入数据
        username.sendKeys("muronghuoxiao2");
        delay(200);
        password.sendKeys("19940203XIN");
        delay(200);
        rememberPassword.click();

        // 获得验证码的地址
        WebElement captchaImage = driver
                .findElement(By.cssSelector("#codePic"));
        String captchaImageUrl = captchaImage.getAttribute("src");

        System.out.println("验证码地址：\n\n" + captchaImageUrl + "\n");
        System.out.println("请输入验证码：");

        // 从控制台输入验证码
        Scanner in = new Scanner(System.in);
        String captcha_value = in.next();
        captcha.sendKeys(captcha_value);

        // 登录
        login.click();

        delay(5000);

        // System.out.println(driver.getPageSource());

        // 获得[药物检索]按钮,并点击
        WebElement search = null;
        while (true) {
            try {
                search = driver
                        .findElement(By
                                .cssSelector("div.nav div.nav-wrap.clear div.nav-items ul.clear li[menuid='ui_medcineSearch'] a"));
                search.click();
                break;
            } catch (Exception e) {
                delay(100);
            }
        }

        delay(5000);

        // 用于存放窗口句柄
        Set<String> handleSet = new HashSet<String>();

        // 当前窗口句柄
        firstHandle = driver.getWindowHandle();
        handleSet.add(firstHandle);
        // 新窗口句柄
        secondHandle = firstHandle;

        // 获得所有窗口句柄
        Set<String> handles = driver.getWindowHandles();
        Iterator it = handles.iterator();
        while (it.hasNext()) {
            secondHandle = (String) it.next();
            // 寻找新增的窗口句柄
            if (!handleSet.contains(secondHandle)) {
                handleSet.add(secondHandle);
                break;
            }
        }

        // 切换到新窗口
        driver.switchTo().window(secondHandle);

        // 申请日=19850910:20171229
        while (true) {
            try {
                driver.switchTo().window(secondHandle);
                WebElement searchExpDisplay = driver.findElement(By
                        .cssSelector("#searchExpDisplay"));
                searchExpDisplay.sendKeys("");
                searchExpDisplay.sendKeys("申请日=19850910:20171229");

                WebElement searchElement = driver.findElement(By
                        .cssSelector("#med_search_btn"));
                searchElement.click();
                break;
            } catch (Exception e) {
                delay(100);
                System.out.println(e);
            }
        }
        // 【1】从检索历史里搜索
        // while (true) {
        // try {
        // search = driver
        // .findElement(By
        // .cssSelector("#common_search_history > div > div > ul > li:nth-child(1) > div > div.history-btn-group.history-row.clear > a.history-btn.history-btn-view.history-right"));
        // search.click();
        // break;
        // } catch (Exception e) {
        // delay(100);
        // System.out.println(e);
        // }
        // }
        // 【2】重新设置参搜索
        // WebElement span =
        // driver.findElement(By.cssSelector("#IMED002select > a"));
        // span.click();
        // delay(1000);
        // WebElement to = driver.findElement(By.cssSelector("#IMED002select > a
        // > ul >
        // li:nth-child(6) > a"));
        // to.click();
        // WebElement year =
        // driver.findElement(By.cssSelector("#inputItemIMED002"));
        // year.sendKeys("19850910 20171229");
        // search = driver.findElement(By.cssSelector("#med_search_btn"));

        delay(5000);
        System.out.println("数据开始加载。。。");

        JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
        delay(1000);

        int num_page = 0;
        while (true) {
            try {
                num_page = Integer
                        .parseInt(driver
                                .findElement(
                                        By.cssSelector("#search_result > div > div.re-content.search-mode-content > div.re-page > div > div > div > div > p:nth-child(6)"))
                                .getText().replace("共", "").replace("页", "")
                                .trim());
                break;
            } catch (Exception e) {
                delay(100);
                System.out.println(e);
            }
        }

        System.out.println("共有" + num_page + "页");

        // 跳转到第*页
        int gotoPageNum = 20000;

        while (true) {
            try {
                WebElement gotoPage = driver
                        .findElement(By.cssSelector("#txt"));
                WebElement buttonOK = driver
                        .findElement(By
                                .cssSelector("#search_result > div > div.re-content.search-mode-content > div.re-page > div > div > div > div > a:nth-child(10)"));
                gotoPage.clear();
                gotoPage.sendKeys("" + gotoPageNum);
                buttonOK.click();
                break;
            } catch (Exception e) {
                delay(100);
                System.out.println(e);
            }
        }
        // 存储数据
        int i = 0;
        while (true) {
            System.out.println("==========第" + (i + 1) + "页=============");

            List<WebElement> elementList = driver
                    .findElements(By
                            .cssSelector("#search_result > div > div.re-content.search-mode-content > div.list-container > ul > li"));
            // #search_result > div > div.re-content.search-mode-content >
            // div.list-container > ul > li
            // #search_result > div > div.re-content.search-mode-content >
            // div.list-container > ul > li:nth-child(2)
            // #search_result > div > div.re-content.search-mode-content >
            // div.list-container > ul > li:nth-child(1)
            infoEntityList.clear();

            for (int j = 0; j < elementList.size(); j++) {
                // System.out.println(j);
                InfoEntity infoEntity = new InfoEntity();
                String[] strs = null;
                WebElement element = null;
                String css = "#search_result > div > div.re-content.search-mode-content > div.list-container > ul > li:nth-child("
                        + (j + 1) + ")";
                while (true) {
                    try {
                        element = driver.findElement(By.cssSelector(css));
                        strs = element.getText().split("\n");
                        break;
                    } catch (Exception e) {
                        delay(100);
                        System.out.println(e);
                        driver.switchTo().window(secondHandle);
                    }
                }
                infoEntity.setAllAttribute(strs);

                // 查看摘要
                WebElement seeDetail = null;
                while (true) {
                    try {
                        seeDetail = element.findElement(By
                                .partialLinkText("查看详细"));
                        Actions action = new Actions(driver);
                        action.click(seeDetail).perform();
                        break;
                    } catch (Exception e) {
                        delay(100);
                        System.out.println(e);
                        element = driver.findElement(By.cssSelector(css));
                        driver.switchTo().window(secondHandle);
                    }
                }

                handles = driver.getWindowHandles();
                it = handles.iterator();
                while (it.hasNext()) {
                    thirdHandle = (String) it.next();
                    // 寻找新增的窗口句柄
                    if (!handleSet.contains(thirdHandle)) {
                        while (true) {
                            try {
                                driver.switchTo().window(thirdHandle);
                                infoEntity
                                        .setSummary(driver
                                                .findElement(
                                                        By.cssSelector("#detailViewPanel > table:nth-child(2) > tbody > tr > td"))
                                                .getText());
                                break;
                            } catch (Exception e) {
                                delay(100);
                                System.out.println(e);
                            }
                        }
                        break;
                    }
                }

                // System.out.println(infoEntity);
                infoEntityList.add(infoEntity);
                driver.switchTo().window(secondHandle);
            }

            // 先滚动到页面底下
            jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");

            while (true) {
                try {
                    WebElement nextButton = driver.findElement(By
                            .linkText("下一页"));
                    nextButton.click();
                    break;
                } catch (Exception e) {
                    delay(100);
                }
            }

            MyAccessDataBase.insertInfoList("表一", infoEntityList);
            System.out.println("成功!");

            i++;
            if (i >= num_page) { // num_page
                break;
            }
        }

        try {
            /**
             * WebDriver自带了一个智能等待的方法。
             * dr.manage().timeouts().implicitlyWait(arg0, arg1）；
             * Arg0：等待的时间长度，int 类型 ； Arg1：等待时间的单位 TimeUnit.SECONDS 一般用秒作为单位。
             */
            driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        driver.quit();
    }

    /***
     * startPage 起始页 endPage 终止页,不包含
     */
    public void download(int startPage, int endPage, String tableName,
                         String username, String password) {
        List<InfoEntity> infoEntityList = new ArrayList<InfoEntity>();

        ChromeOptions options = new ChromeOptions();
        WebDriver driver = new ChromeDriver(options);

        // 加载登录界面
        driver.get(loginUrl);

        delay(100);

        // 获得登录窗口
        WebElement usernameElement = driver.findElement(By.id("j_username"));
        WebElement passwordElement = driver.findElement(By
                .id("j_password_show"));
        WebElement captcha = driver.findElement(By.id("j_validation_code"));
        WebElement rememberPassword = driver.findElement(By
                .id("wee_remember_me"));
        WebElement login = driver.findElement(new ByCssSelector(
                "[class='btn btn-login']"));

        // 写入数据
        usernameElement.sendKeys(username);
        delay(200);
        passwordElement.sendKeys(password);
        delay(200);
        rememberPassword.click();

        // 获得验证码的地址
        WebElement captchaImage = driver
                .findElement(By.cssSelector("#codePic"));
        String captchaImageUrl = captchaImage.getAttribute("src");

        System.out.println("验证码地址：\n\n" + captchaImageUrl + "\n");
        System.out.println("请输入验证码：");

        // 从控制台输入验证码
        Scanner in = new Scanner(System.in);
        String captcha_value = in.next();
        captcha.sendKeys(captcha_value);

        // 登录
        login.click();

        delay(5000);

        // System.out.println(driver.getPageSource());

        // 登录成功
        Set<Cookie> cookies = driver.manage().getCookies();

        // 重新创建连接
        driver.quit();
        options = new ChromeOptions();
//		options.setHeadless(true);
        driver = new ChromeDriver(options);
        driver.get("http://www.pss-system.gov.cn/sipopublicsearch/portal/uiIndex.shtml");

        delay(5000);

        driver.manage().deleteAllCookies();
        for (Cookie cookie : cookies) {
            driver.manage().addCookie(cookie);
        }
        driver.get("http://www.pss-system.gov.cn/sipopublicsearch/portal/uiIndex.shtml");

        // 获得[药物检索]按钮,并点击
        WebElement search = null;
        while (true) {
            try {
                search = driver
                        .findElement(By
                                .cssSelector("div.nav div.nav-wrap.clear div.nav-items ul.clear li[menuid='ui_medcineSearch'] a"));
                search.click();
                break;
            } catch (Exception e) {
                delay(100);
            }
        }

        delay(5000);

        // 用于存放窗口句柄
        Set<String> handleSet = new HashSet<String>();

        // 当前窗口句柄
        firstHandle = driver.getWindowHandle();
        handleSet.add(firstHandle);
        // 新窗口句柄
        secondHandle = firstHandle;

        // 获得所有窗口句柄
        Set<String> handles = driver.getWindowHandles();
        Iterator it = handles.iterator();
        while (it.hasNext()) {
            secondHandle = (String) it.next();
            // 寻找新增的窗口句柄
            if (!handleSet.contains(secondHandle)) {
                handleSet.add(secondHandle);
                break;
            }
        }

        // 切换到新窗口
        driver.switchTo().window(secondHandle);

        // 申请日=19850910:20171229
        while (true) {
            try {
                driver.switchTo().window(secondHandle);
                WebElement searchExpDisplay = driver.findElement(By
                        .cssSelector("#searchExpDisplay"));
                searchExpDisplay.sendKeys("");
                searchExpDisplay.sendKeys("申请日=19850910:20171229");

                WebElement searchElement = driver.findElement(By
                        .cssSelector("#med_search_btn"));
                searchElement.click();
                break;
            } catch (Exception e) {
                delay(100);
                System.out.println(e);
            }
        }
        // 【1】从检索历史里搜索
        // while (true) {
        // try {
        // search = driver
        // .findElement(By
        // .cssSelector("#common_search_history > div > div > ul > li:nth-child(1) > div > div.history-btn-group.history-row.clear > a.history-btn.history-btn-view.history-right"));
        // search.click();
        // break;
        // } catch (Exception e) {
        // delay(100);
        // System.out.println(e);
        // }
        // }
        // 【2】重新设置参搜索
        // WebElement span =
        // driver.findElement(By.cssSelector("#IMED002select > a"));
        // span.click();
        // delay(1000);
        // WebElement to = driver.findElement(By.cssSelector("#IMED002select > a
        // > ul >
        // li:nth-child(6) > a"));
        // to.click();
        // WebElement year =
        // driver.findElement(By.cssSelector("#inputItemIMED002"));
        // year.sendKeys("19850910 20171229");
        // search = driver.findElement(By.cssSelector("#med_search_btn"));

        delay(5000);
        System.out.println("数据开始加载。。。");

        JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");
        delay(1000);

        int num_page = 0;
        while (true) {
            try {
                num_page = Integer
                        .parseInt(driver
                                .findElement(
                                        By.cssSelector("#search_result > div > div.re-content.search-mode-content > div.re-page > div > div > div > div > p:nth-child(6)"))
                                .getText().replace("共", "").replace("页", "")
                                .trim());
                break;
            } catch (Exception e) {
                delay(100);
                System.out.println(e);
            }
        }

        System.out.println("共有" + num_page + "页");

        // 跳转到第startPage页
        while (true) {
            try {
                WebElement gotoPage = driver
                        .findElement(By.cssSelector("#txt"));
                WebElement buttonOK = driver
                        .findElement(By
                                .cssSelector("#search_result > div > div.re-content.search-mode-content > div.re-page > div > div > div > div > a:nth-child(10)"));
                gotoPage.clear();
                gotoPage.sendKeys("" + startPage);
                buttonOK.click();
                break;
            } catch (Exception e) {
                delay(100);
                System.out.println(e);
            }
        }
        // 存储数据
        int i = startPage;
        while (true) {
            System.out.println("==========第" + (i) + "页=============");

            List<WebElement> elementList = driver
                    .findElements(By
                            .cssSelector("#search_result > div > div.re-content.search-mode-content > div.list-container > ul > li"));
            // #search_result > div > div.re-content.search-mode-content >
            // div.list-container > ul > li
            // #search_result > div > div.re-content.search-mode-content >
            // div.list-container > ul > li:nth-child(2)
            // #search_result > div > div.re-content.search-mode-content >
            // div.list-container > ul > li:nth-child(1)
            infoEntityList.clear();

            for (int j = 0; j < elementList.size(); j++) {
                // System.out.println(j);
                InfoEntity infoEntity = new InfoEntity();
                String[] strs = null;
                WebElement element = null;
                String css = "#search_result > div > div.re-content.search-mode-content > div.list-container > ul > li:nth-child("
                        + (j + 1) + ")";
                while (true) {
                    try {
                        element = driver.findElement(By.cssSelector(css));
                        strs = element.getText().split("\n");
                        break;
                    } catch (Exception e) {
                        delay(100);
                        e.printStackTrace();
                        driver.switchTo().window(secondHandle);
                    }
                }
                infoEntity.setAllAttribute(strs);

                // 查看摘要
                WebElement seeDetail = null;
                int times = 0;
                while (true) {
                    try {
                        times++;
                        if (times > 50) {
                            break;
                        }
                        seeDetail = element.findElement(By
                                .partialLinkText("查看详细"));
                        Actions action = new Actions(driver);
                        action.click(seeDetail).perform();
                        break;
                    } catch (Exception e) {
                        delay(500);
                        e.printStackTrace();
                        element = driver.findElement(By.cssSelector(css));
                        driver.switchTo().window(secondHandle);
                    }
                }

                handles = driver.getWindowHandles();
                it = handles.iterator();
                while (it.hasNext()) {
                    thirdHandle = (String) it.next();
                    // 寻找新增的窗口句柄
                    if (!handleSet.contains(thirdHandle)) {
                        while (true) {
                            try {
                                driver.switchTo().window(thirdHandle);
                                infoEntity
                                        .setSummary(driver
                                                .findElement(
                                                        By.cssSelector("#detailViewPanel > table:nth-child(2) > tbody > tr > td"))
                                                .getText());
                                break;
                            } catch (Exception e) {
                                delay(100);
                                e.printStackTrace();
                            }
                        }
                        break;
                    }
                }

                // System.out.println(infoEntity);
                infoEntityList.add(infoEntity);
                driver.switchTo().window(secondHandle);
            }

            // 先滚动到页面底下
            jse.executeScript("window.scrollTo(0, document.body.scrollHeight);");

            while (true) {
                try {
                    WebElement nextButton = driver.findElement(By
                            .linkText("下一页"));
                    nextButton.click();
                    break;
                } catch (Exception e) {
                    delay(100);
                }
            }

            MyAccessDataBase.insertInfoList(tableName, infoEntityList);
            System.out.println("成功!");

            i++;
            if (i >= endPage) { // num_page
                break;
            }
        }

        try {
            /**
             * WebDriver自带了一个智能等待的方法。
             * dr.manage().timeouts().implicitlyWait(arg0, arg1）；
             * Arg0：等待的时间长度，int 类型 ； Arg1：等待时间的单位 TimeUnit.SECONDS 一般用秒作为单位。
             */
            driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        driver.quit();
    }

    public void delay(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void fun1() {
        // 登录
        String url = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/medicineSearch-initMedicineSearch.shtml";
        String url1 = "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/executeMedicineSearch-executeMedicineSearch.shtml";
        Connection conn = Jsoup.connect(url);
        Map<String, String> headsMap = new HashMap<String, String>();
        headsMap.put(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        headsMap.put(
                "Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        headsMap.put("Accept-Encoding", "gzip, deflate");
        headsMap.put("Accept-Language", "zh-CN,zh;q=0.9");
        headsMap.put("Connection", "keep-alive");
        headsMap.put("Content-Length", "218");
        headsMap.put("Content-Type",
                "application/x-www-form-urlencoded; charset=UTF-8");
        headsMap.put(
                "Cookie",
                "IS_LOGIN=true; WEE_SID=GCbeYASmELRJkeX7TNfCmAbSH6DCOPsc98nCahdK3InX4donePpC!-727369456!360229595!1515559322790; wee_username=emhvdXdlaXhpbg%3D%3D; wee_password=MTk5NDAyMDNYSU4%3D; avoid_declare=declare_pass; JSESSIONID=GCbeYASmELRJkeX7TNfCmAbSH6DCOPsc98nCahdK3InX4donePpC!-727369456!360229595");
        headsMap.put("Host", "www.pss-system.gov.cn");
        headsMap.put(
                "Referer",
                "http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/medicineSearch-initMedicineSearch.shtml");
        headsMap.put("Upgrade-Insecure-Requests", "1");
        headsMap.put("X-Requested-With", "XMLHttpRequest");

        Map<String, String> datasMap = new HashMap<String, String>();
        datasMap.put("searchCondition.searchExp", "申请日=20000101:20010101");
        datasMap.put("searchCondition.dbId", "MED");
        datasMap.put("searchCondition.extendInfo['MODE']", "MODE_MEDICINE");
        datasMap.put("searchCondition.searchType", "medicine");
        datasMap.put("wee.bizlog.modulelevel", "02004");

        try {
            Document doc = conn.headers(headsMap).data(datasMap).get();
            System.out.println(doc);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
